package org.framework.sys;


import java.io.IOException;
import java.io.InputStream;

import net.pgia.pub.util.common.StringUtil;

import org.apache.commons.digester.Digester;
import org.apache.log4j.Logger;
import org.framework.app.exception.AppException;
import org.framework.app.exception.SysException;
import org.framework.pub.conn.ConnectionConfigDef;
import org.framework.pub.conn.ConnectionDef;
import org.xml.sax.SAXException;



/**
 * Title: 信息分析系统<br>
 * Description: <br>
 * Date: 2012-8-14 <br>
 * Copyright (c) 2012 PGIASoft<br>
 * 
 * @author zdp
 */
public class SysConfigReader {
	private static Logger log = Logger.getLogger(SysConfigReader.class);
	
	public static final String SYS_CONFIG_FILE = "core-config.xml";

	public static final String ROOT = "core-config";
	public static final String RUN_MODE = "core-config/run-mode";
	public static final String CONNECT_CONFIG = "core-config/connection-config";
	public static final String CONNECTTION = 	"core-config/connection-config/connection";
	public static final String DATASOURCE = 	"core-config/connection-config/connection/datasource";
	public static final String DIRVER_CLASS = 	"core-config/connection-config/connection/driver-class";
	public static final String USERNAME = 		"core-config/connection-config/connection/username";
	public static final String PASSWORD = 		"core-config/connection-config/connection/password";
	public static final String URL = 			"core-config/connection-config/connection/url";
	public static final String POOL_MAX_ACTIVE = "core-config/connection-config/connection/pool-maxActive";
	public static final String POOL_MAX_WAIT = 	"core-config/connection-config/connection/pool-maxWait";
	public static final String POOL_MAX_IDLE = 	"core-config/connection-config/connection/pool-maxIdle";

	private SysConfigDef sysConfigDef = new SysConfigDef();
	
	
	private Digester digester;
	
	private static SysConfigReader  instance = null;
	
	
	
	private SysConfigReader(String path) throws SysException, AppException {
		
		log.debug("开始装载配置文件:" + SYS_CONFIG_FILE);
		InputStream in = SysConfigReader.class.getClassLoader().getResourceAsStream(SYS_CONFIG_FILE);
		this.read(in);
		
		log.debug("成功装载连接配置文件：" + SYS_CONFIG_FILE);
		StringBuffer summary = new StringBuffer("\n");
		summary.append("============================================");
		summary.append("\n 系统配置信息：\n");
		summary.append("run-mode = ");
		summary.append(sysConfigDef.getRunMode());
		summary.append(";\n");
		summary.append("connection-config default = ");
		summary.append(sysConfigDef.getConConfigDef().getDefaultName());
		summary.append(";\n");
		summary.append("============================================");
		log.debug(summary.toString());

	}
	
	
	/**
	 * 初始化单例SysConfigReader对象
	 * 
	 * @return
	 * @throws SysException
	 * @throws AppException
	 */
	public static void init(String path) throws SysException,
			AppException {
		if (null == instance) {
			if (StringUtil.isBlank(path)) {
				throw new AppException("","缺少core-config.xml文件地址参数配置，请检查jvm参数设置！");
			}else{
				log.debug("开始装载core-config.xml文件：" + path);
				instance = new SysConfigReader(path);
				log.debug("SysConfigReader 创建成功。");
			}
			
		}
		
	}
	
	/**
	 * 初始化单例SysConfigReader对象
	 * 
	 * @return
	 * @throws SysException
	 * @throws AppException
	 */
	synchronized public static void init() throws SysException,
			AppException {
		if (null == instance) {
				log.debug("开始装载core-config.xml文件：" + SYS_CONFIG_FILE);
				instance = new SysConfigReader(SYS_CONFIG_FILE);
				log.debug("SysConfigReader 创建成功。");
			
			
		}
		
	}
	
	/**
	 * 从 输入流中按添加的规则读取xml配置信息
	 * @param in
	 * @throws BeansDefinitionException
	 */
	private void read(InputStream in) throws SysException{
		
		digester=new Digester();
		digester.push(this);
		digester.setValidating(false);
		this.addRules();
		try	{
			digester.parse(in);
		}catch(IOException ioe)
		{
			ioe.printStackTrace();
			throw new SysException("xml parse exception",ioe);
		}catch(SAXException saxe)
		{
			saxe.printStackTrace();
			throw new SysException("xml parse exception",saxe);
		}
		
	}
	
	/**
	 * 添加digester的解析规则
	 *
	 */
	public void addRules() 
	{
		digester.addObjectCreate(ROOT,SysConfigDef.class);
		digester.addCallMethod(RUN_MODE,"setRunMode",0);
		
		//Connection Pools parse
		digester.addObjectCreate(CONNECT_CONFIG,ConnectionConfigDef.class);
		digester.addSetProperties(CONNECT_CONFIG,"default","defaultName");
		
		/*
		 * <connection name="weblogic-pool">
				<datasource>ds/hbsps</datasource>
		*  </connection>
		*  <connection name="local-pool">
			<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
			<username>hbspsdev</username>
			<password>hbspsdev</password>
			<url>jdbc:oracle:thin:@133.96.30.10:1521:oracle2</url>
		
			<pool-maxActive>100</pool-maxActive>
			<pool-maxWait>120000</pool-maxWait>
			<pool-maxIdle>10</pool-maxIdle>
		  </connection>
		 */
		digester.addObjectCreate(CONNECTTION,ConnectionDef.class);
		digester.addSetProperties(CONNECTTION,"name","name");
		digester.addCallMethod(DATASOURCE,"setDatasource",0);
		digester.addCallMethod(DIRVER_CLASS,"setDriverClass",0);
		digester.addCallMethod(USERNAME,"setUserName",0);
		digester.addCallMethod(PASSWORD,"setPassword",0);
		digester.addCallMethod(URL,"setUrl",0);
		digester.addCallMethod(POOL_MAX_ACTIVE,"setPoolMaxActive",0);
		digester.addCallMethod(POOL_MAX_IDLE,"setPoolMaxIdle",0);
		digester.addCallMethod(POOL_MAX_WAIT,"setPoolMaxWait",0);
		
		digester.addSetNext(CONNECTTION,"addConnection");
		digester.addSetNext(CONNECT_CONFIG,"setConConfigDef");
		
		digester.addSetNext(ROOT,"setSysConfigDef");
	}
	
	
	
	public static SysConfigDef getSysConfigDef()  {
		if( null == instance){
			SysConfigReader.init();
		}
		return instance.sysConfigDef;
	}

	public void setSysConfigDef(SysConfigDef sysConfigDef) {
		this.sysConfigDef = sysConfigDef;
	}
	
	
	

	public static void main(String[] args)throws Exception{

		SysConfigReader.init();
		
//		SysConfigReader.init("E:/workspace/projects-in-job/fast-projects/pub/src/core-config.xml");
		/*pro = (BeanPropertyDefinition)reader.getBeanDefinition("globalActionHandle").getProperties().get("actions");
		System.out.println(pro.getType()+":"+pro.getCollection().size());
		
		pro = (BeanPropertyDefinition)reader.getBeanDefinition("nodeActionDispatcher").getProperties().get("actions");
		System.out.println(pro.getType()+":"+pro.getCollection().size());*/
		
	
	}

	
	
	

}
